package org.springcloud.wisdom.spring_01_canteen.indent;

import com.alibaba.fastjson.JSON;
import org.springcloud.wisdom.spring_01_canteen.common.util.RandomUtil;
import org.springcloud.wisdom.spring_01_canteen.mall.websocket.WebSocketServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class IndentService {

    private final IndentDao indentDao;
    @Autowired
    private WebSocketServer webSocketServer;

    @Autowired
    public IndentService(IndentDao indentDao) {
        this.indentDao = indentDao;
    }

    // 生成包含时间戳和随机两位数的订单号
    private String generateOrderId() {
        long timestamp = System.currentTimeMillis();
        String timestampStr = String.valueOf(timestamp).substring(0, 13);
        int randomTwoDigits = (int) (Math.random() * 100);
        return timestampStr + String.format("%02d", randomTwoDigits);
    }

    // 添加订单
    public String addIndent(Indent indent) {
        indent.setIndentid(generateOrderId());

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateTimeString = sdf.format(new Date());
        indent.setOrderdate(dateTimeString);
        // 插入订单逻辑
        Integer rowsAffected = indentDao.insertIndent(indent);
        return (rowsAffected > 0)? indent.getIndentid() : null;
    }

    // 查看所有订单，可以根据需要添加参数进行筛选，例如按买家ID
    public List<Indent> getAllIndents(Integer mallid) {
        return indentDao.selectAllIndents(mallid);
    }

    public Indent getAllIndents1(String indentid) {
        //通过websocket向客户端推送
        Map map = new HashMap<>();
        map.put("type",1);
        map.put("OrderId",indentid);
        map.put("content","订单号："+indentid);
        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
        System.out.println("json"+json);
        return indentDao.selectAllIndents1(indentid);
    }

    public Indent getAllIndents2(String indentid) {


        return indentDao.selectAllIndents1(indentid);
    }

    // 修改订单状态
    public boolean updatesign(Indent indent){
        return indentDao.updatesign(indent)>0;
    }

    // 获取所有订单的数量
    public int getAllOrderCount() {
        return indentDao.countIndents();
    }

    // 根据日期获取订单数量
    public int getOrderCountByDate(Date date,Integer mallid) {
        return indentDao.countIndentsByDateAndMid(date,mallid);
    }

    //查看商家营业额
    public BigDecimal sumTotalPriceByMallId(Integer mallid) {
        return indentDao.sumTotalPriceByMallId(mallid);
    }
}